<template>
  <div class="voucher-page">
    <Timeline
      v-model="selectedMonth"
      :months="monthList"
      class="timeline-panel"
    />


    <div class="voucher-content">
      <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">

            <a-form-item label="" class="smart-query-form-item" name="name">
                <a-input v-model:value="searchParam.name" placeholder="请输入摘要" />
            </a-form-item>
            <a-form-item class="smart-query-form-item smart-margin-left10">
                <a-button type="primary" @click="search">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="reset" style="margin-left: 6px;">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
                <a-button type="primary" @click="addVoucher" style="margin-left: 6px;">
                    新增凭证
                </a-button>
                <a-button type="danger" @click="deleteVoucher" style="margin-left: 6px;">
                    删除
                </a-button>
                <a-button type="primary" @click="auditVoucher" style="margin-left: 6px;">
                    审核
                </a-button>
                <a-button type="primary" @click="printVoucher" style="margin-left: 6px;">
                    打印
                </a-button>
                <a-button type="primary" @click="exportVoucher" style="margin-left: 6px;">
                    导出
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
      <table class="voucher-table" ref="voucherTableRef">
        <thead>
          <tr>
            <th style="width: 48px; text-align: center;">
              <input type="checkbox" :checked="isAllSelected" @change="onSelectAll($event)" />
            </th>
            <th>摘要</th>
            <th>科目</th>
            <th>借方金额</th>
            <th>贷方金额</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="group in voucherGroups" :key="group.id">
            <!-- 头部 -->
            <tr class="voucher-header">
              <td style="text-align: center;">
                <input type="checkbox" :checked="selectedRowKeys.includes(group.id)" @change="onSelectGroup(group.id, $event)" />
              </td>
              <td colspan="4">
                <span style="color:#1890ff;">{{ group.date }}</span>
                &nbsp;{{ group.code }}&nbsp;
                附单据：{{ group.attachments }}张
                来源：{{ group.source }}
                审核人：{{ group.reviewer }}
              </td>
            </tr>
            <!-- 明细 -->
            <tr v-for="(item, idx) in group.details" :key="group.id + '-' + idx">
              <td></td>
              <td>{{ idx === 0 ? group.summary : '' }}</td>
              <td>{{ item.subject }}</td>
              <td>{{ item.debit !== null ? item.debit.toFixed(2) : '' }}</td>
              <td>{{ item.credit !== null ? item.credit.toFixed(2) : '' }}</td>
            </tr>
            <!-- 合计 -->
            <tr class="voucher-total">
              <td></td>
              <td>{{ group.total.summary }}</td>
              <td></td>
              <td>{{ group.total.debit.toFixed(2) }}</td>
              <td>{{ group.total.credit.toFixed(2) }}</td>
            </tr>
          </template>
        </tbody>
      </table>

    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import Timeline from '../components/Timeline.vue';
import html2canvas from 'html2canvas';

const searchDate = ref([]);
const searchParam = ref({});


const monthList = [
  { label: '1月', value: '2025-01' },
  { label: '2月', value: '2025-02' },
  { label: '3月', value: '2025-03' },
  { label: '4月', value: '2025-04' },
  { label: '5月', value: '2025-05' },
  { label: '6月', value: '2025-06' },
  { label: '7月', value: '2025-07' },
  { label: '8月', value: '2025-08' },
  { label: '9月', value: '2025-09' },
  { label: '10月', value: '2025-10' },
  { label: '11月', value: '2025-11' },
  { label: '12月', value: '2025-12' }
];
const selectedMonth = ref(monthList[3].value); // 默认4月

const voucherGroups = ref([
  {
    id: 1,
    date: '2025-04-30',
    code: '记-001',
    attachments: 1,
    source: '销项发票',
    reviewer: '王泽文',
    summary: '营业收入,2025-04-01,服务费,广东涛睿管业科技有限公司',
    details: [
      {
        subject: '1122 应收账款-00543 广东涛睿管业科技有限公司',
        debit: 4500.00,
        credit: null,
      },
      {
        subject: '500109 主营业收入-服务费',
        debit: null,
        credit: 4455.45,
      },
      {
        subject: '22210111 应交税费-应交增值税-小规模增值税',
        debit: null,
        credit: 44.55,
      }
    ],
    total: {
      summary: '合计：肆仟伍佰元整',
      debit: 4500.00,
      credit: 4500.00
    }
  },
  {
    id: 2,
    date: '2025-04-30',
    code: '记-002',
    attachments: 2,
    source: '销项发票',
    reviewer: '王泽文',
    summary: '营业收入,2025-04-01,服务费,佛山市高明区顶尖妇婴用品实业有限公司',
    details: [
      {
        subject: '1122 应收账款-00340 佛山市高明区顶尖妇婴用品实业有限公司',
        debit: 8334.00,
        credit: null,
      },
      {
        subject: '500109 主营业收入-服务费',
        debit: null,
        credit: 8251.49,
      },
      {
        subject: '22210111 应交税费-应交增值税-小规模增值税',
        debit: null,
        credit: 82.51,
      }
    ],
    total: {
      summary: '合计：捌仟叁佰叁拾肆元整',
      debit: 8334.00,
      credit: 8334.00
    }
  }
]);
const selectedRowKeys = ref([]);

function onSelectGroup(id, event) {
  if (event.target.checked) {
    if (!selectedRowKeys.value.includes(id)) {
      selectedRowKeys.value.push(id);
    }
  } else {
    selectedRowKeys.value = selectedRowKeys.value.filter(key => key !== id);
  }
}

// a-table 对比用数据（将所有明细平铺）
const flatDetails = computed(() => {
  let arr = [];
  voucherGroups.value.forEach(group => {
    group.details.forEach((item, idx) => {
      arr.push({
        rowKey: group.id + '-' + idx,
        groupId: group.id,
        date: group.date,
        code: group.code,
        summary: idx === 0 ? group.summary : '',
        subject: item.subject,
        debit: item.debit,
        credit: item.credit,
        reviewer: group.reviewer,
        source: group.source
      });
    });
  });
  return arr;
});

const columns = [
  { title: '摘要', dataIndex: 'summary' },
  { title: '科目', dataIndex: 'subject' },
  { title: '借方金额', dataIndex: 'debit',
    customRender: ({ text }) => text !== null && text !== undefined ? Number(text).toFixed(2) : '' },
  { title: '贷方金额', dataIndex: 'credit',
    customRender: ({ text }) => text !== null && text !== undefined ? Number(text).toFixed(2) : '' },
];

const isAllSelected = computed(() => selectedRowKeys.value.length === voucherGroups.value.length && voucherGroups.value.length > 0);

function onSelectAll(event) {
  if (event.target.checked) {
    selectedRowKeys.value = voucherGroups.value.map(g => g.id);
  } else {
    selectedRowKeys.value = [];
  }
}

function addVoucher() {
  console.log('新增凭证');
}

function deleteVoucher() {
  console.log('删除凭证');
}

function auditVoucher() {
  console.log('审核凭证');
}

const voucherTableRef = ref(null);

async function printVoucher() {
  if (!voucherTableRef.value) return;
  const canvas = await html2canvas(voucherTableRef.value, {
    backgroundColor: '#fff',
    scale: 2 // 提高清晰度
  });
  const link = document.createElement('a');
  link.href = canvas.toDataURL('image/png');
  link.download = '凭证表.png';
  link.click();
}

function exportVoucher() {
  console.log('导出凭证');
}
</script>

<style scoped>
.voucher-page {
  display: flex;
  flex-direction: row;
  height: 100%;
}
.timeline-panel {
  width: 100px;
  margin-right: 16px;
}
.voucher-content {
  flex: 1;
}
.voucher-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}
.voucher-table th, .voucher-table td {
  border: 1px solid #e8e8e8;
  padding: 8px;
  text-align: left;
}
.voucher-header {
  background: #f6faff;
  font-weight: bold;
}
.voucher-total {
  background: #fafafa;
  font-weight: bold;
}
</style>